// @ts-nocheck

import React, { FC, useState, useEffect, useMemo } from "react";
import {
  NavBar,
  Button,
  Form,
  Input,
  Cascader,
  ImageUploader,
  Toast,
} from "antd-mobile";
import { Spin } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import { CascaderOption } from "antd-mobile/es/components/cascader";
import { getListToOptions } from "@/utils/tools";
import { HandOk } from "@/components";
// service
import { authorize, upLoadImage, residentialList } from "./service";
import { getCurrentUser } from "@/utils/authority";
// style
import "./index.less";
interface IFormState {
  title: string;
  type: string[];
  content: string;
}

interface IStartFormState {
  questiontitle: string;
  eventType: string;
  discoveryTime: string;
  eventNo: string; //事件编号
  fileFront: string[];
}

function CommunityServiceReport() {
  const location = useLocation();
  const [defaultInfo, setDefaultInfo] = useState();
  const [disabled, setDisabled] = useState(false);
  useEffect(() => {
    if (location.state.defaultInfo) {
      console.log(location.state.defaultInfo);
      setDefaultInfo(location.state.defaultInfo);
      form.setFieldsValue(location.state.defaultInfo);
      setDisabled(true);
    }
  }, [location.state]);
  // 当前服务上报类型
  const [eventReportType, setEventReportType] = useState();
  const userInfo = getCurrentUser();

  const [form] = Form.useForm();
  const navigate = useNavigate();

  const [visible, setVisible] = useState(false);
  const [plotVisible, setPlotVisible] = useState(false);
  const [ImageList, setImageList] = useState<{ url: string; name: string }[]>(
    []
  );
  const [eventList, setEventList] = useState<CascaderOption[]>([
    {
      label: "广安市",
      value: "1782593290671837185",
      children: [
        {
          label: "中桥街道",
          value: "1782593290671837185",
          children: [
            {
              label: "解放社区",
              value: "1782593290671837185",
            },
          ],
        },
      ],
    },
  ]);
  const [plotList, setPlotList] = useState<CascaderOption[]>([
    {
      label: "南城印象",
      value: "南城印象",
    },
  ]);
  const [loaing, setLoaing] = useState(false);
  const [handOk, setHandOk] = useState(false);

  const getUserType = async () => {
    try {
      const { data } = await residentialList();
      const arr = (Array.isArray(data) ? data : []).map((v) => ({
        label: v.residentialName,
        value: v.residentialId,
      }));
      setPlotList(arr);
    } catch {}
  };

  useEffect(() => {
    getUserType();
  }, []);

  const onFinish = async (values: IFormState) => {
    const attachList: string[] = ImageList.map((item) => {
      return item.url;
    });
    setLoaing(true);
    const formCommitData: IStartFormState = {
      ...values,
      userId: userInfo?.user_id,
      residentialId: values.residentialId[values.residentialId.length - 1],
      deptId: values.deptId[values.deptId.length - 1],
      phone: values.phone,
      avatar: attachList?.[0],
    };
    console.log(formCommitData);

    try {
      const parma = formCommitData;
      const { code } = await authorize(parma);
      if (code != 200) {
        Toast.show({
          icon: "fail",
          content: "认证失败",
        });
        setLoaing(false);
        setHandOk(false);
        return;
      }
      if (code == 200) {
        setLoaing(false);
        Toast.show({
          icon: "success",
          content: "认证成功",
        });
        setHandOk(true);
      }
    } catch (err) {
      console.error(err);
    }
  };

  const getEventOptions = (x: any) => {
    const obj: CascaderOption = {
      label: x.categoryCompleteName,
      value: x.categoryCompleteName,
    };
    if (x?.categoryChild) {
      obj["children"] = getListToOptions(x.categoryChild, getEventOptions);
    }
    return obj;
  };

  async function mockUpload(file: File) {
    try {
      const { data } = await upLoadImage({ file: file });
      if (data?.code === 200) {
        Toast.show({
          icon: "success",
          content: "上传成功",
        });

        const url = data.data.length && data.data[0].link;
        const name = data.data.length && data.data[0].name;
        return {
          url,
          name,
        };
      } else {
        Toast.show({
          icon: "fail",
          content: "上传失败,该文件类型被限制上传",
        });
        return {
          url: "",
        };
      }
    } catch (err) {
      Toast.show({
        icon: "fail",
        content: "上传失败",
      });
      return {
        url: "",
      };
    }
  }

  const Basic = useMemo(() => {
    return (
      <div>
        <div className="figImg">多添加图片，能更清晰的表明事件地点</div>
        <ImageUploader
          value={ImageList}
          onChange={setImageList}
          upload={mockUpload}
          multiple={false}
          maxCount={1}
          capture={true}
          showUpload={ImageList.length < 1}
        />
      </div>
    );
  }, [ImageList]);

  return handOk ? (
    <HandOk title="我们将尽快与您联系" header={eventReportType} />
  ) : (
    <Spin tip="提交中..." spinning={loaing}>
      <div className="reportcontent">
        <div>
          <NavBar onBack={() => navigate("/")}>
            <div className="commontitle">社区认证</div>
          </NavBar>
        </div>

        <div className="eventFrom">
          <Form
            form={form}
            onFinish={onFinish}
            initialValues={{
              phone: userInfo?.account,
            }}
            disabled={disabled}
          >
            <Form.Item
              name="deptId"
              label="所属社区"
              trigger="onConfirm"
              onClick={() => {
                setVisible(true);
              }}
              rules={[{ required: true, message: "必填项" }]}
            >
              <Cascader
                options={eventList}
                visible={visible}
                onClose={() => {
                  setVisible(false);
                }}
              >
                {(items) => {
                  if (items.every((item) => item === null)) {
                    return <div className="colour">点击选择所属社区</div>;
                  } else {
                    return items
                      .map((item) => item?.label ?? "未选择")
                      .join("-");
                  }
                }}
              </Cascader>
            </Form.Item>
            <Form.Item
              name="userName"
              label="姓名"
              rules={[{ required: true, message: "必填项" }]}
            >
              <Input placeholder="请输入事件名称" />
            </Form.Item>
            <Form.Item
              name="phone"
              label="联系电话"
              rules={[{ required: true, message: "必填项" }]}
            >
              <Input placeholder="请输入手机号码" disabled />
            </Form.Item>
            <Form.Item
              name="residentialId"
              label="我的小区"
              trigger="onConfirm"
              onClick={() => {
                setPlotVisible(true);
              }}
              rules={[{ required: true, message: "必填项" }]}
            >
              <Cascader
                options={plotList}
                visible={plotVisible}
                onClose={() => {
                  setPlotVisible(false);
                }}
              >
                {(items) => {
                  if (items.every((item) => item === null)) {
                    return <div className="colour">点击选择所属小区</div>;
                  } else {
                    return items[items.length - 1]?.label;
                  }
                }}
              </Cascader>
            </Form.Item>
            <Form.Item
              label="照片"
              rules={[{ required: true, message: "必填项" }]}
              className="BasicBox"
            >
              {Basic}
            </Form.Item>
            {!defaultInfo && (
              <div className="bottomButton" style={{ margin: "0" }}>
                <Button
                  onClick={(e) => {
                    if (!loaing) {
                      e.preventDefault();
                      form.submit();
                    }
                  }}
                  type="submit"
                  className="reportbtn "
                  style={{ fontSize: "1.5rem" }}
                >
                  {loaing ? "提交中" : "提交"}
                </Button>
              </div>
            )}
          </Form>
        </div>
      </div>
    </Spin>
  );
}

export default CommunityServiceReport;
